package com.smarttiger.zero.logic.impl;

import com.smarttiger.zero.admin.entity.ArgsModel;
import com.smarttiger.zero.admin.util.Constant;
import com.smarttiger.zero.admin.webservice.TransferUtil;
import com.smarttiger.zero.logic.BaseLogic;
import com.smarttiger.zero.logic.InterfaceContext;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by zhouzhengwei on 2021/10/25.
 */
@Component
public class WebServiceLogic extends BaseLogic {

    @Override
    public void logic() {
        HashMap<String,Object> test = new HashMap();
        List<ArgsModel> argsModels = getArgsModels();
        Map paramValue = (Map)getParamValue(Constant.INTERFACECURRENT);
        String wsdl = "";
        String method = "";
        List<Object> params = new ArrayList<>();
        for (ArgsModel map : argsModels) {
            if(map.getName().equals("wsdl")){
                wsdl = map.getDefaultValue();
            }else if(map.getName().equals("method")){
                method = map.getDefaultValue();
            }else{
                Object param = paramValue.get(map.getName());
                if(param != null){
                    Object object = TransferUtil.transferJ2W(map.getTypecode(),param);
                    params.add(object);
                }else if(!StringUtils.isEmpty(map.getDefaultValue())){
                    Object object = TransferUtil.transferJ2W(map.getTypecode(), TransferUtil.transferS2J(map.getTypecode(),map.getDefaultValue().toString()));
                    params.add(object);
                }
            }
        }

        if(wsdl.length() == 0){
            Map<String, String> controll = InterfaceContext.logicControlContext.get();
            if(controll == null){
                controll = new HashMap<>();
            }
            controll.put(InterfaceContext.CONTROLL_ERROR,"wsdl参数没有设置");
            return;
        }
        if(method.length() == 0){
            Map<String, String> controll = InterfaceContext.logicControlContext.get();
            if(controll == null){
                controll = new HashMap<>();
            }
            controll.put(InterfaceContext.CONTROLL_ERROR,"method参数没有设置");
            return;
        }

        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(wsdl);
        Object[] objects = new Object[0];
        try {
            objects = client.invoke(method, params.toArray(new String[params.size()]));
        } catch (Exception e) {
            e.printStackTrace();
        }
        setCurrentValue("data",objects[0]);
        setResult(objects[0]);
    }
}
